package com.mlm.mlmapp.utils;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Administrator on 2016/4/19 0019.
 */
public class DownloadUtil extends Thread{



        private Context mContext;

        private Handler mHandler;

        private String mDownloadUrl; // 文件下载url，已做非空检查

        private String mFileName;

        private Message msg;



        private final String APP_FOLDER = "MLM"; // sd卡应用目录

        private final String APK_FOLDER = "apkFile"; // 下载apk文件目录



        public static final int MSG_UNDOWN = 0; //未开始下载

        public static final int MSG_DOWNING = 1; // 下载中

        public static final int MSG_FINISH = 99; // 下载完成

        public static final int MSG_FAILURE = 2;// 下载失败



        private NotificationManager mNotifManager;

        private Notification mDownNotification;

        private RemoteViews mContentView; // 下载进度View

        private PendingIntent mDownPendingIntent;



        public DownloadUtil(Context context, Handler handler,

                                String downloadUrl, String fileName) {

            mContext = context;

            mHandler = handler;

            mDownloadUrl = downloadUrl;

            mFileName = fileName;

            mNotifManager = (NotificationManager) mContext

                    .getSystemService(Context.NOTIFICATION_SERVICE);

            msg = new Message();

        }



        @Override

        public void run() {
            Message downingMsg=null;
            try {

                if (Environment.getExternalStorageState().equals(

                        Environment.MEDIA_MOUNTED)) {

                    downingMsg = new Message();
                    downingMsg.what = MSG_DOWNING;

                    mHandler.sendMessage(downingMsg);

                    // SD卡准备好

                    File sdcardDir = Environment.getExternalStorageDirectory();


                    File folder = new File(sdcardDir

                            + File.separator + APP_FOLDER);

                    if (!folder.exists()) {

                        //创建存放目录
                        folder.mkdir();

                    }

                    File saveFilePath = new File(folder, mFileName);
                    boolean downSuc = downloadFile(mDownloadUrl, saveFilePath);

                } else {
                    Toast.makeText(mContext, Environment.getExternalStorageState(),

                            Toast.LENGTH_SHORT).show();


                }

            } catch (Exception e) {
                Log.e("sort", "run: "+e.getMessage() );

            } finally {


            }

        }



        /**

         *

         * Desc:文件下载

         *

         * @param downloadUrl

         *            下载URL

         * @param saveFilePath

         *            保存文件路径

         * @return ture:下载成功false:下载失败

         */

        public boolean downloadFile(String downloadUrl, File saveFilePath) {
            int fileSize = -1;

            int downFileSize = 0;

            boolean result = false;

            int progress = 0;

            try {

                URL url = new URL(downloadUrl);

                HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                if (null == conn) {

                    return false;

                }

                // 读取超时时间 毫秒级

                conn.setReadTimeout(10000);

                conn.setRequestMethod("GET");

                conn.setDoInput(true);

                conn.connect();

                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {

                    fileSize = conn.getContentLength();

                    InputStream is = conn.getInputStream();

                    FileOutputStream fos = new FileOutputStream(saveFilePath);

                    byte[] buffer = new byte[1024*1024];

                    int i = 0;

                    int tempProgress = -1;

                    while ((i = is.read(buffer)) != -1) {
                        msg=new Message();
                        downFileSize = downFileSize + i;

                        // 下载进度

                        progress = (int) (downFileSize * 100.0 / fileSize);
                        fos.write(buffer, 0, i);
                            if (progress==100) {
                                msg.what=MSG_FINISH;
                                msg.obj=saveFilePath;
                                mHandler.sendMessage(msg);
                            } else if (tempProgress != progress) {
                                msg.what=MSG_DOWNING;
                                msg.arg1= progress;
                                tempProgress = progress;
                                mHandler.sendMessage(msg);

                            }

                        }


                    fos.flush();

                    fos.close();

                    is.close();

                    result = true;

                } else {

                    result = false;

                }

            } catch (Exception e) {
                Log.e("sort", "downloadFile: "+e.getMessage() );
                result = false;


            }

            return result;

        }

}
